/**手机端两列瀑布流 */

import React, { useEffect, useRef, useState } from "react";
import styles from "./index.module.less";
import "./index.less";
import { useNavigate, useLocation } from "react-router-dom";
import { request } from "@apis/request";

const ShowCateGoods = () => {
    const [datas, setDatas] = useState([]);

    const navigate = useNavigate();
    const local = useLocation();
    const wrap = useRef(null);
    const column1 = useRef(null);
    const column2 = useRef(null);

    let height1 = 0;
    let height2 = 0;
    let page = 1;
    let data = []; // 当前要加载的数据
    const showNum = 10; // 每次添加10条新数据
    // 图片实际宽度
    const width = (document.documentElement.clientHeight / 1080) * 400;
    // 生成虚拟节点，减少重排重绘次数
    const f1 = document.createDocumentFragment();
    const f2 = document.createDocumentFragment();

    // 添加每条数据对应的dom
    const addDom = () => {
        data = datas.slice((page - 1) * showNum, page * showNum);
        console.log("data: ", data);
        if (data.length === 0) return;
        for (let i = 0; i < data.length; i++) {
            const _item = document.createElement("div");
            _item.classList.add("item");
            const img = new Image();
            // img.src = data[i].img
            img.dataset.src = data[i].goodsImages[0].img;
            img.dataset.sellerUserName = data[i].userName;
            img.dataset.goodsId = data[i].goodsId;
            img.dataset.price = data[i].price;
            img.classList.add("goods_img");
            _item.appendChild(img);
            const _goods_msg = document.createElement("div");
            _goods_msg.classList.add("goods_msg");
            const _gmoney_msg = document.createElement("div");
            _gmoney_msg.classList.add("gmoney_msg");
            const _seller_msg = document.createElement("div");
            _seller_msg.classList.add("seller_msg");
            if (Math.random() > 0.5) {
                const p1_1 = document.createElement("p");
                p1_1.classList.add("p1");
                p1_1.innerHTML = "包邮";
                _goods_msg.appendChild(p1_1);
            }
            const p2_1 = document.createElement("p");
            p2_1.innerHTML = data[i].goodsName + "/" + data[i].brand;
            p2_1.classList.add("p2");
            _goods_msg.appendChild(p2_1);
            if (!data[i].isAcceptCutPrice) {
                const p1_2 = document.createElement("p");
                p1_2.classList.add("p1");
                p1_2.innerHTML = "不可议价";
                _gmoney_msg.appendChild(p1_2);
            }
            const p2_2 = document.createElement("p");
            p2_2.innerHTML = data[i].price + " G币";
            p2_2.classList.add("p2");
            _gmoney_msg.appendChild(p2_2);
            const _seller_avatar = document.createElement("div");
            _seller_avatar.classList.add("seller_avatar");
            const _img = new Image();
            _seller_msg.appendChild(_seller_avatar);
            _seller_avatar.appendChild(_img);
            const _seller_nick = document.createElement("div");
            _seller_nick.classList.add("seller_nick");
            _seller_nick.innerHTML = data[i].userName;
            _seller_msg.appendChild(_seller_nick);
            _item.appendChild(_goods_msg);
            _item.appendChild(_gmoney_msg);
            _item.appendChild(_seller_msg);

            if (height1 <= height2) {
                f1.appendChild(_item);
                height1 += Math.round(
                    ((data[i].goodsImages[0].height + 130) * width) /
                        data[i].goodsImages[0].width
                );
            } else {
                f2.appendChild(_item);
                height2 += Math.round(
                    ((data[i].goodsImages[0].height + 130) * width) /
                        data[i].goodsImages[0].width
                );
            }
            // console.log(height1, height2)
        }
        column1.current.appendChild(f1);
        column2.current.appendChild(f2);
        page++;
        lazyLoadImage();
    };

    // 图片懒加载
    const lazyLoadImage = () => {
        const imgs = document.querySelectorAll(".goods_img");
        const observer = new IntersectionObserver(function (entries) {
            entries.forEach((item) => {
                if (item.isIntersecting) {
                    item.target.setAttribute("src", item.target.dataset.src);
                    observer.unobserve(item.target);
                }
            });
            if (entries.length === 1) {
                console.log(imgs[imgs.length - 1].src);
                // 如果当前最后一张图片出现在可视区，就开始插入下一页dom
                if (imgs[imgs.length - 1].src) {
                    addDom();
                }
            }
        });
        imgs.forEach((item) => {
            // 观察每张图片
            observer.observe(item);
        });
    };

    useEffect(() => {
        async function getCateDatas() {
            const res = await request("/mall/getCateList");
            console.log("res: ", res);
            if (res.code === "0000") {
                const list = res.data;
                let result = [];
                switch (local.pathname) {
                    case "/m/mall/goodsRecommend":
                        setDatas(list);
                        break;
                    case "/m/mall/electronics":
                        result = list.filter(
                            (item) => item.goodsCate === "电子产品"
                        );
                        setDatas(result);
                        break;
                    case "/m/mall/homeAppliances":
                        result = list.filter(
                            (item) => item.goodsCate === "家用电器"
                        );
                        setDatas(result);
                        break;
                    case "/m/mall/officeSupplies":
                        result = list.filter(
                            (item) => item.goodsCate === "办公用品"
                        );
                        setDatas(result);
                        break;
                    case "/m/mall/schoolThings":
                        result = list.filter(
                            (item) => item.goodsCate === "学习用品"
                        );
                        setDatas(result);
                        break;
                    case "/m/mall/wearMatch":
                        result = list.filter(
                            (item) => item.goodsCate === "穿搭相关"
                        );
                        setDatas(result);
                        break;
                    case "/m/mall/snackDepartment":
                        result = list.filter(
                            (item) => item.goodsCate === "零食百货"
                        );
                        setDatas(result);
                        break;
                    default:
                        setDatas([]);
                }
            } else {
                console.log(res.msg);
            }
        }
        getCateDatas();
    }, [local.pathname]);

    useEffect(() => {
        column1.current.innerHTML = "";
        column2.current.innerHTML = "";
        addDom();
    });

    useEffect(() => {
        wrap.current.addEventListener("click", function (e) {
            const imgs = document.querySelectorAll(".goods_img");
            const _imgs = Array.from(imgs);
            if (_imgs.includes(e.target)) {
                // 携带/形式的路由参数跳转
                // navigate(`/m/goodsDetails/${e.target.dataset.goodsId}`)
                // 携带?形式的路由参数跳转
                navigate(
                    `/m/goodsDetails?goodsId=${e.target.dataset.goodsId}&sellerUserName=${e.target.dataset.sellerUserName}&price=${e.target.dataset.price}`
                );
            }
        });
    });

    return (
        <div className={styles.showCateGoods} ref={wrap} id="catewrap">
            <div className={styles.column1} ref={column1}></div>
            <div className={styles.column2} ref={column2}></div>
        </div>
    );
};

export default ShowCateGoods;
